package com.example.repository;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public class UserRepositoryImpl implements UserRepository {
    private final SqlSessionFactory sqlSessionFactory;

    public UserRepositoryImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public User getUserById(String id) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            return session.getMapper(UserMapper.class).getUserById(id);
        }
    }

    @Override
    public void insertUser(User user) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            session.getMapper(UserMapper.class).insertUser(user);
            session.commit();
        }
    }

    @Override
    public void deleteUserById(String id) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            session.getMapper(UserMapper.class).deleteUserById(id);
            session.commit();
        }
    }

    @Override
    public void updateUser(User user) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            session.getMapper(UserMapper.class).updateUser(user);
            session.commit();
        }
    }

    @Override
    public List<User> getAllUsers() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            return session.getMapper(UserMapper.class).getAllUsers();
        }
    }
}